package com.netty.websocket;

import com.alibaba.fastjson.JSONObject;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public final class MessageCache {
    public ConcurrentHashMap<String, ConcurrentLinkedQueue<JSONObject>> mapMessageCache = new ConcurrentHashMap();
    public ConcurrentHashMap<String,Integer> mapQueueSize =new ConcurrentHashMap();//记录所有队列的values计数
    public ConcurrentHashMap<String,Integer> mapCodes =new ConcurrentHashMap();

    public String name;

    public static ConcurrentHashMap<String,MessageCache> mapCache=new ConcurrentHashMap();//记录所有队列的SingleQueue
    public static MessageCache newOrFind(String name) {
        if(mapCache==null)mapCache=new ConcurrentHashMap();
        MessageCache cache = mapCache.get(name);
        if (cache == null) {
            cache = new MessageCache();
            cache.name=name;
            mapCache.put(name, cache);
        }
        return cache;
    }

    public void add(JSONObject msgJSON) {
        ConcurrentLinkedQueue<JSONObject> concurrentLinkedQueue = mapMessageCache.get(name);
        if (concurrentLinkedQueue == null) {
            concurrentLinkedQueue = new ConcurrentLinkedQueue();//java 队列容器
            mapMessageCache.put(name, concurrentLinkedQueue);
            mapQueueSize.put(name,0);
        }

        String __code=msgJSON.getString("__code");
        if (__code==null || __code.length()==0){
            concurrentLinkedQueue.add(msgJSON);
        }else if (!mapCodes.containsKey(__code)){
            mapCodes.put(__code,1);
            concurrentLinkedQueue.add(msgJSON);
        }

        mapQueueSize.put(name,concurrentLinkedQueue.size());
    }

    public JSONObject poll() {
        ConcurrentLinkedQueue<JSONObject> concurrentLinkedQueue = mapMessageCache.get(name);
        if (concurrentLinkedQueue == null) {
            Integer size=mapQueueSize.get(name);
            mapQueueSize.put(name,size==null?0:size - 1);
            return null;
        }

        return concurrentLinkedQueue.poll();//获取并删除一个
    }

    public int size(){
        Integer size=mapQueueSize.get(name);
        return size==null?0:size;
    }
}
